package com.hoperun.checkcloth.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hoperun.checkcloth.R;
import com.hoperun.checkcloth.base.MIP_BaseActivity;
import com.hoperun.checkcloth.net.IServiceImpl;
import com.hoperun.checkcloth.net.RequestServiceImpl;
import com.hoperun.checkcloth.ui.dialog.SimpleDialog;
import com.hoperun.checkcloth.util.SharedPreUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class JyFirstShureActivity extends MIP_BaseActivity implements View.OnClickListener {
    RecyclerView recylistview;
    TextView usertextview,input_dateTv,titlesecond,buhaolab,textbqg;
    LinearLayout input_dateLl,listlay,centerlay;
    EditText editbizno,editreson;
    List<JSONObject> jyfirstlist = new ArrayList<JSONObject>();
    QuickAdapter quickAdapter;
    String mJobDate;
    String empID;
    JSONObject resultjson=null;

    private SimpleDateFormat dateFormat_CHINA = new SimpleDateFormat("yyyy年MM月dd日");
    private SimpleDateFormat dateFormat_EN = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_jy_first_shure);

        recylistview=(RecyclerView)this.findViewById(R.id.recylistview);
        usertextview=(TextView)this.findViewById(R.id.usertextview);
        input_dateTv=(TextView)this.findViewById(R.id.input_dateTv);
        input_dateLl=(LinearLayout)this.findViewById(R.id.input_dateLl);
        editbizno=(EditText)this.findViewById(R.id.editbizno);
        listlay=(LinearLayout)this.findViewById(R.id.listlay);
        centerlay=(LinearLayout)this.findViewById(R.id.centerlay);
        titlesecond=(TextView)this.findViewById(R.id.titlesecond);
        buhaolab=(TextView)this.findViewById(R.id.buhaolab);
        textbqg=(TextView)this.findViewById(R.id.textbqg);
        editreson=(EditText)this.findViewById(R.id.editreson);

        this.findViewById(R.id.shureBtn).setOnClickListener(this);
        this.findViewById(R.id.notshure).setOnClickListener(this);
        this.findViewById(R.id.input_dateLl).setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylistview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recylistview.setAdapter(quickAdapter);
        recylistview.setHasFixedSize(true);
        recylistview.setNestedScrollingEnabled(false);
        RequestServiceImpl.jy_getsysdate(mMIPHandler, IServiceImpl.JY_GETTIME);

        empID = (String) SharedPreUtil.getValue(this,
                SharedPreUtil.YHBH, "");
        usertextview.setText("检验工："+empID);

        editbizno.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {

                    String monadNo = editbizno.getText().toString().trim();
                    if (monadNo.length() >= 4) {
                        querysanlian(monadNo);
                    } else {
                        showSimpleDialog(getResources().getString(R.string.monadno_not_right));
                    }
                    return true;
                }
                return false;
            }
        });
    }
    public class QuickAdapter extends BaseQuickAdapter<JSONObject, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.item_firstshure, jyfirstlist);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final JSONObject item) {
            TextView item_sanlian = holder.getView(R.id.item_sanlian);
            TextView  item_buhao= holder.getView(R.id.item_buhao);
            TextView  item_haoquan= holder.getView(R.id.item_haoquan);
            TextView  item_first= holder.getView(R.id.item_first);
            TextView  item_second= holder.getView(R.id.item_second);

            item_sanlian.setText(item.optString("CLOTHTKTNO")== null ? "" : item.optString("CLOTHTKTNO").toString());
            item_buhao.setText(item.optString("CLOTHNO")== null ? "" : item.optString("CLOTHNO").toString());
            item_haoquan.setText(item.optString("BQGXM")== null ? "" : item.optString("BQGXM").toString());
            if(jyfirstlist.size()==1){
                item_second.setVisibility(View.GONE);
                item_first.setText(item.optString("ONECAUSE")== null ? "" : item.optString("ONECAUSE").toString());
            }else{
                item_second.setVisibility(View.VISIBLE);
                if(holder.getLayoutPosition()==0){
                    item_first.setText(item.optString("ONECAUSE")== null ? "" : item.optString("ONECAUSE").toString());
                }else{
                    item_second.setText(item.optString("TWOCAUSE")== null ? "" : item.optString("TWOCAUSE").toString());
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.input_dateLl:
                setDate();
                break;
            case R.id.shureBtn:
                if(resultjson==null){
                    showSimpleDialog("暂无有效数据");
                    return;
                }

                showWait();
                RequestServiceImpl.jy_shurebqg(mMIPHandler, IServiceImpl.JY_SHUREFIRST,  empID, (String) SharedPreUtil.getValue(this,
                        SharedPreUtil.YHMC, ""),editreson.getEditableText().toString().trim(),resultjson,jyfirstlist);
              break;
            case R.id.notshure:
                if(resultjson==null){
                    showSimpleDialog("暂无有效数据");
                    return;
                }

                if(editreson.getEditableText().toString().length()==0){
                    showSimpleDialog("请输入原因");
                    return;
                }
                if(jyfirstlist.size()==2){
                    showSimpleDialog("最多两次不确认");
                    return;
                }
                showWait();
                RequestServiceImpl.jy_notshurebqg(mMIPHandler, IServiceImpl.JY_NOTSHUREFIRST,  empID, (String) SharedPreUtil.getValue(this,
                        SharedPreUtil.YHMC, ""),editreson.getEditableText().toString().trim(),resultjson,jyfirstlist);
                break;
        }
    }

    public void querysanlian(String CLOTHTKTNO) {
        showWait();
        RequestServiceImpl.jy_queryfirstshure(mMIPHandler, IServiceImpl.JY_QUERYFIRST, CLOTHTKTNO);
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
            switch (requestType) {
                case IServiceImpl.JY_QUERYFIRST://根据条件查询
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                             resultjson= jsonObj.optJSONObject("DATA");
                             JSONArray myarray= resultjson.optJSONArray("LIST");
                            if (myarray != null&&myarray.length()>0) {
                                jyfirstlist.clear();
                                for (int i = 0; i < myarray.length(); i++) {
                                     JSONObject one=myarray.getJSONObject(i);
                                     jyfirstlist.add(one);
                                }
                                listlay.setVisibility(View.VISIBLE);
                                if(jyfirstlist.size()==1){
                                    titlesecond.setVisibility(View.GONE);
                                }else{
                                    titlesecond.setVisibility(View.VISIBLE);
                                }
                                quickAdapter.notifyDataSetChanged();

                            }else {
                                listlay.setVisibility(View.GONE);
                                jyfirstlist.clear();
                            }
                            centerlay.setVisibility(View.VISIBLE);
                            String mm=resultjson.optString("CLOTHNO")== null ? "" : resultjson.optString("CLOTHNO").toString();
                            buhaolab.setText("布号："+mm);
                            String bqg=resultjson.optString("BQGXM")== null ? "" : resultjson.optString("BQGXM").toString();
                            textbqg.setText("保全工："+bqg);
                            editreson.setText("");

                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("查询出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_SHUREFIRST://保存
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            resultjson=null;
                            jyfirstlist.clear();
                            listlay.setVisibility(View.GONE);
                            centerlay.setVisibility(View.GONE);
                            showSimpleDialog("确认成功！");
                            editbizno.setText("");
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("保存出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_NOTSHUREFIRST:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("MSG_INFO");
                        opt = jsonObj.optString("OPT_FLAG");
                        if ("SUCCESS".equals(opt)) {
                            resultjson=null;
                            jyfirstlist.clear();
                            listlay.setVisibility(View.GONE);
                            centerlay.setVisibility(View.GONE);
                            showSimpleDialog("不确认成功！");
                            editbizno.setText("");
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                showSimpleDialog("保存出错");
                            } else {
                                showSimpleDialog(msg);
                            }

                        }

                    }catch (Exception e){
                    }
                    break;
                case IServiceImpl.JY_GETTIME://获取时间
                    try {
                        if (!TextUtils.isEmpty((String) objBody)) {
                            mJobDate=dateFormat_EN.format(dateFormat_EN.parse(objBody.toString()));
                            input_dateTv.setText(dateFormat_CHINA.format(dateFormat_EN.parse(objBody.toString())));
                        }

                    }catch (Exception e){
                    }


            }
    }


    private void showSimpleDialog(String message) {
        SimpleDialog.Companion.newInstance(message).show(getSupportFragmentManager(), "DialogTip");
    }



    /**
     * 设置日期
     */
    private void setDate() {
        String[] strNow = mJobDate.toString().split("-");
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, mOnDateSetListenernew, Integer.parseInt(strNow[0]), Integer.parseInt(strNow[1])-1, Integer.parseInt(strNow[2]));
        datePickerDialog.show();
    }

    /**
     * 日期选择监听器
     */
    DatePickerDialog.OnDateSetListener mOnDateSetListenernew = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year + "年" + String.format("%02d", month + 1) + "月" + String.format("%02d", dayOfMonth)+"日";
            input_dateTv.setText(date);
            mJobDate = year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth);

        }
    };

}